import axios from 'axios';

// 开发环境通过 vue.config.js 的代理转发到后端
// 生产环境可使用环境变量配置真实后端地址
const API_BASE = process.env.NODE_ENV === 'development'
  ? '/api'
  : (process.env.VUE_APP_API_BASE || 'http://localhost:8000');

export function register(code, password) {
  return axios.post(`${API_BASE}/auth/register`, { code, password });
}

export function loginWithCode(code, password) {
  return axios.post(`${API_BASE}/auth/login`, { code, password });
}

// 兼容：如果仍想用用户名登录
export function login(code, password) {
  return axios.post(`${API_BASE}/auth/login`, { code, password });
}

// 请求拦截：自动携带 Bearer Token（优先后端支持的多通道，Header 最标准）
axios.interceptors.request.use((config) => {
  try {
    const token = (typeof window !== 'undefined') ? localStorage.getItem('token') : null
    if (token) {
      config.headers = config.headers || {}
      // 仅在未显式提供 Authorization 时注入
      if (!config.headers.Authorization && !config.headers.authorization) {
        config.headers.Authorization = `Bearer ${token}`
      }
    }
  } catch (_) { /* noop */ void 0 }
  return config
})

// 响应拦截：遇到 401 统一跳转登录，保留当前路径
axios.interceptors.response.use(
  (resp) => resp,
  (error) => {
    try {
      const status = error?.response?.status
      if (status === 401 && typeof window !== 'undefined') {
        const current = window.location.pathname + window.location.search + window.location.hash
        // 避免在登录页上出现循环
        if (!current.startsWith('/login')) {
          const loginUrl = `/login?redirect=${encodeURIComponent(current)}`
          window.location.assign(loginUrl)
        }
      }
    } catch (_) { /* noop */ void 0 }
    return Promise.reject(error)
  }
)

export function getRecommendMovies(token, top_k) {
  const params = { token }
  if (typeof top_k === 'number') params.top_k = top_k
  return axios.get(`${API_BASE}/recommend/movies`, { params });
}

export function rateMovie(token, movie_id, score) {
  return axios.post(`${API_BASE}/recommend/rate`, { token, movie_id, score });
}

export function getMovieDetail(movie_id) {
  return axios.get(`${API_BASE}/recommend/movie/${movie_id}`);
}

export function getMovieRatings(movie_id, limit = 10) {
  return axios.get(`${API_BASE}/recommend/movie/${movie_id}/ratings`, { params: { limit } });
}

export function getUserRatings(token, limit) {
  const params = { token }
  if (typeof limit === 'number') params.limit = limit
  return axios.get(`${API_BASE}/recommend/user/ratings`, { params });
}

export function getSimilarMovies(movie_id, top_k = 12) {
  return axios.get(`${API_BASE}/recommend/movie/${movie_id}/similar`, { params: { top_k } });
}

export function getStreamUrl(movie_id) {
  // 直接返回视频流地址；开发环境通过 /api 代理，可避免跨域
  return `${API_BASE}/recommend/stream/${movie_id}`;
}

// 影片可用视频资源（正片/预告片）
export function getMovieVideos(movie_id) {
  return axios.get(`${API_BASE}/recommend/movie/${movie_id}/videos`)
}

export function getTrailerUrl(movie_id) {
  return `${API_BASE}/recommend/trailer/${movie_id}`
}

// 电影目录（全部电影）分页筛选
export function getMovieCatalog({ page = 1, page_size = 28, genre = '', year_range = '', lang = '', sort = 'hot', q = '' } = {}) {
  const params = { page, page_size }
  if (genre) params.genre = genre
  if (year_range) params.year_range = year_range
  if (lang) params.lang = lang
  if (sort) params.sort = sort
  if (q) params.q = q
  return axios.get(`${API_BASE}/recommend/catalog`, { params })
}

// 电影目录可选项（类型/年份范围）
export function getMovieCatalogOptions() {
  return axios.get(`${API_BASE}/recommend/catalog/options`)
}